//
//  ViewController.m
//  JianChaRiBao
//
//  Created by yuzhou on 13-5-8.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>

#import "MagazineViewController.h"
#import "ListenViewController.h"
#import "NovelViewController.h"

#import "IndexSelectView.h"
#import "AccountViewController.h"
#import "ActivateViewController.h"
#import "DynamicsViewController.h"
#import "IndexViewController.h"
#import "ShelfViewController.h"
@interface ViewController ()
{
    ActivateViewController * accountViewCon;
    
    IndexViewController *indexViewController;
    ShelfViewController *shelfViewController;
    
    MagazineViewController *magazineViewController;
    ListenViewController *listenViewController;
    NovelViewController *novelViewController;
    
    IndexSelectView *indexSelectView;
    
    DynamicsViewController * dynamicsViewController;
    
    NSMutableArray *indexArray;
    
    NSString *nickname;
    
    int currentTab;
    
}
@end

@implementation ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _currentIndex = -1;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkDynamicsUpdate) name:UIApplicationDidBecomeActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showActiveView) name:@"ShowActiveView" object:nil];
    }
    return self;
}
-(void)showActiveView{
    [self showAccountView];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
//    NSURL * url = [[NSBundle mainBundle] URLForResource:@"app/zhong" withExtension:@"html"];
//    [anmiateWebView loadRequest:[NSURLRequest requestWithURL:url]];
//    anmiateWebView.delegate = self;
    
    //添加子控制器
    indexViewController = [[[IndexViewController alloc] initWithNibName:@"IndexViewController" bundle:nil] autorelease];
    shelfViewController = [[[ShelfViewController alloc] initWithNibName:@"ShelfViewController" bundle:nil] autorelease];
    dynamicsViewController = [[[DynamicsViewController alloc]initWithNibName:@"DynamicsViewController" bundle:nil]autorelease];
//    magazineViewController = [[[MagazineViewController alloc] initWithNibName:@"MagazineViewController" bundle:nil] autorelease];
//    listenViewController = [[[ListenViewController alloc] initWithNibName:@"ListenViewController" bundle:nil] autorelease];
//    novelViewController = [[[NovelViewController alloc] initWithNibName:@"NovelViewController" bundle:nil] autorelease];
    
    [containerViewController addChildViewController:indexViewController];
    [containerViewController addChildViewController:shelfViewController];
    [containerViewController addChildViewController:dynamicsViewController];
    
    
    
//    [containerViewController addChildViewController:listenViewController];
//    [containerViewController addChildViewController:novelViewController];
//    [containerViewController addChildViewController:shelfViewController];
    
    //目录数组
    indexArray = [[NSMutableArray alloc] init];
    [indexArray addObject:@{@"index":@(kNewsIndex),@"name":@"报纸",@"image":@"index_news"}];
    [indexArray addObject:@{@"index":@(kMagazineIndex),@"name":@"杂志",@"image":@"index_magazine"}];
    [indexArray addObject:@{@"index":@(kListenIndex),@"name":@"听书",@"image":@"index_listen"}];
    [indexArray addObject:@{@"index":@(kNovelIndex),@"name":@"图书",@"image":@"index_novel"}];
    [indexArray addObject:@{@"index":@(kMainIndex),@"name":@"首页",@"image":@"index_main"}];
    
//    self.currentIndex = kMagazineIndex;
    
    //添加tab按钮点击事件
    for(UIView *view in tabBar.subviews) {
        if ([view isKindOfClass:[UIView class]]) {
            UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tabDidSeleted:)];
            [view addGestureRecognizer:tapGesture];
            [tapGesture release];
        }
    }
    
    //添加遮盖视图点击事件
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideMenu)];
    [maskView addGestureRecognizer:tapGesture];
    [tapGesture release];
    
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(hideMenu)];
    swipeGesture.direction = UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft;
    [maskView addGestureRecognizer:swipeGesture];
    [swipeGesture release];
    
    //阴影效果
    mainView.layer.shadowColor = [UIColor blackColor].CGColor;
    mainView.layer.shadowOpacity = 0.45;
    mainView.layer.shadowOffset = CGSizeMake(0, 6);
    mainView.layer.shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 320, 548)].CGPath;
    mainView.layer.masksToBounds = NO;
    
    accountViewCon = [[ActivateViewController alloc]initWithNibName:@"ActivateViewController" bundle:nil];
    [accountView addSubview:accountViewCon.view];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [containerViewController viewDidAppear:YES];
    if (currentTab == 0) {
        [self switchToTab:kTabIndex];
    }
    if (self.currentIndex == -1) {
        self.currentIndex = kMainIndex;
    }
}

- (void)setCurrentIndex:(int)index
{
    _currentIndex = index;
    indexNameLabel.text = [[indexArray objectAtIndex:index] objectForKey:@"name"];
    indexImageView.image = [UIImage imageNamed:[[indexArray objectAtIndex:index] objectForKey:@"image"]];
    if (index == kMainIndex) {
        indexImageView.image = [UIImage imageNamed:@"tab_index"];
    }
    [indexViewController switchToIndex:index];
    [shelfViewController switchToIndex:index];
}

//-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//    NSLog(@"url:%@",request.URL.absoluteString);
//    if ([request.URL.absoluteString rangeOfString:@"tab.html"].length) {
//        NSLog(@"aaadf");
//        [anmiateWebView removeFromSuperview];
//        return NO;
//    }
//    return YES;
//}

- (void)tabDidSeleted:(UITapGestureRecognizer *)gesture
{
    [self switchToTab:gesture.view.tag];
}

- (void)switchToTab:(int)tag
{
//    if (tag == currentTab) {
//        return;
//    }
    
    if (tag != kTabAccount) {
        currentTab = tag;
        [UIView animateWithDuration:0.3 animations:^{
            tabIndicator.center = [[tabBar viewWithTag:tag] center];
        }];
    }
    
    switch (tag) {
        case kTabIndex:
            if (containerViewController.currentViewController == indexViewController) {
                if (indexSelectView == nil) {
                    indexSelectView = [[[[NSBundle mainBundle] loadNibNamed:@"IndexSelectView" owner:self options:nil] objectAtIndex:0] retain];
                    indexSelectView.frame = mainView.bounds;
                }
                NSMutableArray *otherIndexArray = [NSMutableArray arrayWithArray:indexArray];
                [otherIndexArray removeObjectAtIndex:self.currentIndex];
                indexSelectView.indexArray = otherIndexArray;
                indexSelectView.isShelf = NO;
                [indexSelectView updateDisplay];
                [mainView addSubview:indexSelectView];
            }
            [containerViewController transitionFromViewController:containerViewController.currentViewController toViewController:indexViewController duration:0 options:UIViewAnimationOptionCurveEaseInOut animations:nil completion:nil];
            break;
        case kTabShelf:
            if (containerViewController.currentViewController == shelfViewController) {
                if (indexSelectView == nil) {
                    indexSelectView = [[[[NSBundle mainBundle] loadNibNamed:@"IndexSelectView" owner:self options:nil] objectAtIndex:0] retain];
                    indexSelectView.frame = mainView.bounds;
                }
                
                NSMutableArray *otherIndexArray = [NSMutableArray arrayWithArray:indexArray];
                [otherIndexArray removeLastObject];
                indexSelectView.indexArray = otherIndexArray;
                indexSelectView.isShelf = YES;
                [indexSelectView updateDisplay];
                [mainView addSubview:indexSelectView];
            }
            [containerViewController transitionFromViewController:containerViewController.currentViewController toViewController:shelfViewController duration:0 options:UIViewAnimationOptionCurveEaseInOut animations:nil completion:nil];
            break;
        case kTabAnnouncement:
            [containerViewController transitionFromViewController:containerViewController.currentViewController toViewController:dynamicsViewController duration:0 options:UIViewAnimationOptionCurveEaseInOut animations:nil completion:nil];
            dynamicIndicator.hidden = YES;
            break;
        case kTabAccount:
            [self showAccountView];
            break;
        default:
            break;
    }
}

- (void)showWidgetView
{
    widgetView.hidden = NO;
    accountView.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = mainView.frame;
        rect.origin.x = 120;
        mainView.frame = rect;
        
        maskView.alpha = 0.3;
    }];
}

- (void)showAccountView
{
    //在点击个人界面的时候记录一下这个时候是否激活
    if ([[NSUserDefaults standardUserDefaults]objectForKey:EndTime]) {
        isActivedWhenShowMenu = YES;
    }
    widgetView.hidden = YES;
    accountView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = mainView.frame;
        rect.origin.x = -280;
        mainView.frame = rect;
        
        maskView.alpha = 0.3;
    }];
}

- (void)updateWidgetView:(UIView *)view
{
    NSLog(@"view:%@",view);
    for (UIView *v in widgetView.subviews) {
        [v removeFromSuperview];
    }
    view.frame = CGRectMake(0, 20, widgetView.bounds.size.width, widgetView.bounds.size.height - 20);
    
    [widgetView addSubview:view];
    view.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    NSLog(@"view:%@",view);
}

- (void)hideMenu
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = mainView.frame;
        rect.origin.x = 0;
        mainView.frame = rect;
        maskView.alpha = 0;
    }];
    NSLog(@"homepage:%@",[[NSUserDefaults standardUserDefaults]objectForKey:EndTime]);
    if ([[NSUserDefaults standardUserDefaults]objectForKey:EndTime] && !isActivedWhenShowMenu) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"HomePageActived" object:nil];
    }
    [self becomeFirstResponder];
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)checkDynamicsUpdate
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        BOOL update = [[DataRequest sharedRequest] checkDynamicsUpdate];
        dispatch_async(dispatch_get_main_queue(), ^{
            dynamicIndicator.hidden = !update;
        });
    });
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [accountViewCon release];
    [tabBar release];
    [tabIndicator release];
    [mainView release];
    [maskView release];
    [containerViewController release];
    [indexImageView release];
    [indexNameLabel release];
    [widgetView release];
    [accountView release];    
//    [anmiateWebView release];
    [dynamicIndicator release];
    [super dealloc];
}
- (void)viewDidUnload {
    [tabBar release];
    tabBar = nil;
    [tabIndicator release];
    tabIndicator = nil;
    [mainView release];
    mainView = nil;
    [maskView release];
    maskView = nil;
    [containerViewController release];
    containerViewController = nil;
    [indexImageView release];
    indexImageView = nil;
    [indexNameLabel release];
    indexNameLabel = nil;
    [widgetView release];
    widgetView = nil;
    [accountView release];
    accountView = nil;
    [accountViewCon release];
    accountViewCon = nil;
//    [anmiateWebView release];
//    anmiateWebView = nil;
    [super viewDidUnload];
}
@end
